<script lang="tsx" setup>
import type { TreeOption } from 'naive-ui';
import { NButton, NPopconfirm, NSwitch, useDialog, useMessage } from 'naive-ui';
import { h, ref, toRefs } from 'vue';
import { Icon } from '@iconify/vue';
import { useBoolean } from '@sa/hooks';
import { changeStatus, delUser, deptTreeSelect, getPageList } from '@/service/api/system/user';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import { $t } from '@/locales';
import { useDict } from '@/utils/dict';
import SvgIcon from '@/components/custom/svg-icon.vue';
import type { UserChangeStatus, UserVO } from '@/service/types/system';
import ExportModal from '@/components/custom/export-modal.vue';
import UserSearch from './components/user-search.vue';
import ResetPassword from './components/reset-password.vue';
import UserForm from './components/user-form.vue';
import UserDetails from './components/user-details.vue';
import UserImport from './components/user-import.vue';
import UserAuthrole from './components/user-authrole.vue';
const { bool: visible, setTrue: openModal } = useBoolean();
const { bool: drawershow, setTrue: openDrawer } = useBoolean();
const { bool: importVisible, setTrue: openImportModal } = useBoolean();
const { bool: exportVisible, setTrue: openExportModal } = useBoolean();
const { bool: show, setTrue: openShow } = useBoolean();
const dialog = useDialog();
const currentRowId = ref<number | undefined | string>(undefined);
const message = useMessage();
const appStore = useAppStore();
const { sys_user_sex, sys_normal_disable } = toRefs<any>(useDict('sys_user_sex', 'sys_normal_disable'));

const handleResetPassword = (row: UserVO) => {
  currentRowId.value = row.userId;
  openModal();
};
// 修改状态
const changeUserStatus = (id: number | string, value: boolean) => {
  const params = { userId: id, status: value ? '0' : '1' } as UserChangeStatus;
  const messageObj = message.loading('正在修改状态');
  changeStatus(params).then(({ data }) => {
    messageObj.destroy();
    message.success(data.msg);
  });
};

const handleShowDetail = (id: number | string) => {
  currentRowId.value = id;
  openDrawer();
};
const editor = (id: number | string) => {
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
  customerEdit(id);
};
async function handleDelete(id: number | string | number[] | string[]) {
  const { data, error } = await delUser(id as number[]);
  if (!error) {
    message.success(data?.msg);
    onDeleted();
  }
}
const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: getPageList,
  showTotal: true,
  apiParams: {
    pageNum: 1,
    pageSize: 15,
    userName: null,
    phonenumber: null,
    sex: null,
    email: null,
    status: null,
    nickName: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48,
      disabled(row: UserVO) {
        return row.userId === 1;
      }
    },
    {
      key: 'userName',
      title: $t('page.manage.user.userName'),
      align: 'center',
      minWidth: 100
    },
    {
      key: 'nickName',
      title: $t('page.manage.user.nickName'),
      align: 'center',
      minWidth: 100
    },
    {
      key: 'deptName',
      title: '部门名称',
      align: 'center',
      minWidth: 100
    },
    {
      key: 'phonenumber',
      title: $t('page.manage.user.userPhone'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'email',
      title: '邮箱',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      render: (row: any) => {
        let checked = false;
        switch (row.status) {
          case '0':
            checked = true;
            break;
          default:
            checked = false;
            break;
        }
        return (
          <NSwitch
            default-value={checked}
            disabled={row.userId === 1}
            on-update:value={(value: boolean) => {
              changeUserStatus(row.userId, value);
            }}
            size="medium"
            v-slots={{
              checked: () => <div>启用</div>,
              unchecked: () => <div>禁用</div>
            }}
          ></NSwitch>
        );
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 200,
      render: row => {
        return (
          <>
            {row.userId !== 1 && (
              <div class="flex-center gap-10px">
                <NButton
                  tag="a"
                  type="primary"
                  text
                  size="small"
                  onClick={() => {
                    handleShowDetail(row?.userId);
                  }}
                >
                  {{
                    icon: () => <SvgIcon icon="heroicons-solid:magnifying-glass" />
                  }}
                </NButton>

                <NButton
                  tag="a"
                  type="primary"
                  text
                  size="small"
                  onClick={() => {
                    editor(row?.userId);
                  }}
                >
                  {{
                    icon: () => <SvgIcon icon="ant-design:edit-outlined" />
                  }}
                </NButton>
                <NButton
                  tag="a"
                  text
                  type="warning"
                  size="small"
                  onClick={() => {
                    handleResetPassword(row);
                  }}
                >
                  {{
                    icon: () => <SvgIcon icon="grommet-icons:power-reset" />
                  }}
                </NButton>
                <NPopconfirm
                  onPositiveClick={() => {
                    handleDelete(row.userId);
                  }}
                  onNegativeClick={() => {
                    message.info('已取消删除');
                  }}
                >
                  {{
                    default: () => `确认删除当前：${row?.userName} 用户吗?`,
                    trigger: () => (
                      <NButton tag="a" type="error" text size="small" onClick={() => {}}>
                        {{
                          icon: () => <SvgIcon icon="ant-design:delete-outlined" />
                        }}
                      </NButton>
                    )
                  }}
                </NPopconfirm>

                <NButton
                  tag="a"
                  text
                  size="small"
                  onClick={() => {
                    openShow();
                  }}
                >
                  {{
                    icon: () => <SvgIcon icon="mdi:account-arrow-right-outline" />
                  }}
                </NButton>
              </div>
            )}
          </>
        );
      }
    }
  ]
});
const {
  drawerVisible,
  operateType,
  currentId,
  handleAdd,
  customerEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData, 'userId');

const renderPrefix = () => {
  return <Icon icon="clarity:organization-line" class="font-size-4" />;
};
const deptDataTree = ref([]);
// 请求部门树
const getDeptTreeList = () => {
  deptTreeSelect().then((res: any) => {
    deptDataTree.value = res?.data?.data;
  });
};
getDeptTreeList();
// 树节点点击事件
const nodeProps = ({ option }: { option: TreeOption }) => {
  return {
    onClick() {
      searchParams.deptId = option.id as number;
      getData();
    }
  };
};
const options = ref([
  {
    label: '导入数据',
    key: 'import',
    icon: () => {
      return <SvgIcon icon="tabler:file-import" style={{ fontSize: '16px' }} />;
    }
  },
  {
    label: '导出数据',
    key: 'export',
    icon: () => {
      return <SvgIcon icon="mdi:cloud-download-outline" style={{ fontSize: '16px' }} />;
    }
  }
]);
const handleSelect = (key: string | number) => {
  // eslint-disable-next-line default-case
  switch (String(key)) {
    case 'import':
      openImportModal();
      break;
    case 'export':
      openExportModal();
  }
};
async function handleBatchDelete() {
  dialog.warning({
    title: '警告',
    content: '你确定删除这些用户吗?',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { data, error } = await delUser(checkedRowKeys.value as unknown as number[]);
      if (!error) {
        message.success(data?.msg);
        onBatchDeleted();
      }
    },
    onNegativeClick: () => {
      message.info('取消删除');
    }
  });
  // onBatchDeleted();
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch overflow-hidden lt-sm:overflow-auto">
    <NGrid cols="24" item-responsive responsive="screen" class="overflow-hidden">
      <NGridItem class="border-right" span="24 s:24 m:4 l:4 xl:4 2xl:4">
        <NCard
          title="组织列表"
          :bordered="false"
          size="small"
          content-class="lt-sm:overflow-auto h-100% min-h-800px flex-col-stretch sm:flex-1-hidden gap-16px overflow-hidden sm:h-full"
        >
          <template #default>
            <NTabs type="segment" animated>
              <NTabPane name="chap1" tab="部门">
                <NTree
                  block-line
                  :render-prefix="renderPrefix"
                  :data="deptDataTree"
                  key-field="id"
                  label-field="label"
                  :node-props="nodeProps"
                  children-field="children"
                />
              </NTabPane>
              <NTabPane name="chap3" tab="角色">123123</NTabPane>
            </NTabs>
          </template>
        </NCard>
      </NGridItem>
      <NGridItem class="max-height" span="24 s:24 m:20 l:20 xl:20 2xl:20">
        <div class="h-100% min-h-500px flex-col-stretch overflow-hidden lt-sm:overflow-auto">
          <UserSearch
            v-model:model="searchParams"
            :sys-user-sex="sys_user_sex"
            :sys-normal-disable="sys_normal_disable"
            @reset="resetSearchParams"
            @search="getData"
          />
          <NCard :title="$t('page.manage.user.title')" :bordered="false" size="small" class="sm:flex-1-hidden">
            <template #header-extra>
              <TableHeaderOperation
                v-model:columns="columnChecks"
                :disabled-delete="checkedRowKeys.length === 0"
                :loading="loading"
                :checked-row-keys="checkedRowKeys"
                @add="handleAdd"
                @refresh="getData"
                @delete="handleBatchDelete"
              >
                <template #extend>
                  <NDropdown trigger="hover" :options="options" @select="handleSelect">
                    <NButton size="small">
                      <div class="flex flex-row flex-gap-2">
                        <div>其他操作</div>
                        <SvgIcon icon="solar:alt-arrow-down-linear" />
                      </div>
                    </NButton>
                  </NDropdown>
                </template>
              </TableHeaderOperation>
            </template>
            <NDataTable
              v-model:checked-row-keys="checkedRowKeys"
              :columns="columns"
              :data="data"
              size="small"
              :flex-height="!appStore.isMobile"
              :scroll-x="962"
              :loading="loading"
              remote
              :row-key="row => row.userId"
              :pagination="mobilePagination"
              class="sm:h-full"
            >
              <template #empty>
                <Empty />
              </template>
            </NDataTable>
          </NCard>
        </div>
      </NGridItem>
    </NGrid>
    <UserDetails v-model:visible="drawershow" :row-id="currentRowId" :sys-user-sex="sys_user_sex" />
    <ResetPassword v-model:visible="visible" :current-row-id="currentRowId" />
    <UserForm
      v-model:visible="drawerVisible"
      :operate-type="operateType"
      :current-id="currentId"
      :dept-data="deptDataTree"
      :sys-user-sex="sys_user_sex"
      :sys-normal-disable="sys_normal_disable"
      @submitted="getData"
    />
    <UserImport
      v-model:importVisible="importVisible"
      :sys-user-sex="sys_user_sex"
      :sys-normal-disable="sys_normal_disable"
      :dept-data="deptDataTree"
      @submitted="getData"
    />
    <ExportModal
      v-model:exportVisible="exportVisible"
      :search-params="searchParams"
      url="system/user/export"
      :columns="columns"
      title="导出用户数据"
    />
    <UserAuthrole v-model:show="show" />
  </div>
</template>

<style lang="scss" scoped>
.border-right {
  border-right: 1px;
  border-style: solid;
  border-color: var(--un-default-border-color, #e5e7eb);
}
</style>
